package com.nj.dms.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.catalina.tribes.util.Arrays;

/**
 * 登录验证过滤器 如果当前用户已经登录，就放行使用系统所有的功能 如果没有登录，则要求必须重新登录
 * 
 */
@WebFilter(urlPatterns = "/*", initParams = {
		@WebInitParam(name = "initParams", value = ".css;.js;.bmp;.gif;.jpg;.jpeg;.png;login.jsp;ImageRandeCode") })
public class LoginFilter implements Filter {

	String[] initParams = null;

	// 通过init()方法获取设置的过滤参数
	public void init(FilterConfig fConfig) throws ServletException {
		// 调用String类的split()方法将初始化参数按";"拆分为数组元素
		initParams = fConfig.getInitParameter("initParams").split(";");
		// System.out.println(Arrays.toString(initParams) + " - " + this.getClass());

	}

	/**
	 * 实现登录验证的方法
	 */
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		// System.out.println("登录过滤器执行一次" + this.getClass());

		// 获取当前用户的session
		// 1通过HttpServletRequest对象的getSession()方法获取session
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		HttpSession session = request.getSession();
		// 2通过session对象的getAttribute()方法获取到username属性的值
		String userName = (String) session.getAttribute("userName");
		// 获取当前文件的相对地址
		String uriPath = request.getRequestURI();

		// 处理放行多种情况
		// 1通过for循环处理可以放行的资源
		for (String initParam : initParams) {
			if (uriPath.endsWith(initParam)) {
				chain.doFilter(req, res);
				return;
			}
		}
		// 2已经登录的用户，放行
		if (userName != null) {
			// 通过FilterChain的doFilter()方法将request对象和response对象传递下去
			chain.doFilter(req, res);
			return;
		}
		// 3如果当前url地址为loginServlet 提交方法为post放行
		if (uriPath.contains("LoginServlet") && "post".equalsIgnoreCase(request.getMethod())) {
			chain.doFilter(req, res);
			return;
		}
		// 没有登录的用户和不符合以上条件的必须重新登录

		response.sendRedirect(request.getContextPath() + "/login/login.jsp");

	}

	public void destroy() {
	}
}
